//
//  DHRefreshControl.swift
//
//  Created by Holfioo on 15/9/9.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit
// 最大的拖拽量。超过小于这个开始刷新
private let DHRefreshMaxOffset: CGFloat = -60

class DHRefreshControl: UIRefreshControl {
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        setupUI()
    }
    // KVO监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //
        if frame.origin.y > 0 {
            return
        }
        if refreshing {
            refreshView.loadAnimation()
            return
        }
        
        if frame.origin.y < DHRefreshMaxOffset && refreshView.rotation == false {
            // 反过来
            printLog("拿大顶")
            refreshView.rotation = true
            refreshView.descLab.text = "松开释放"
        } else if frame.origin.y > DHRefreshMaxOffset && refreshView.rotation == true {
            printLog("正过来")
            refreshView.rotation = false
            refreshView.descLab.text = "下拉刷新"
        }
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.downView.hidden = true
        refreshView.loadAnimation()
        refreshView.descLab.text = "正在刷新"
    }
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.downView.hidden = false
        refreshView.stopAnimation()
    }
    private func setupUI() {
        // KVO监听frame
        addObserver(self, forKeyPath: "frame", options: [], context: nil)
        
        // 隐藏自身转轮
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(type: ff_AlignType.TopCenter, referView: self, size: nil, offset: CGPoint(x: -40, y: 10))
    }
    // 希构函数
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    private lazy var refreshView: DHRefreshView = DHRefreshView()
}


class DHRefreshView: UIView {
    // 定一个旋转标记
    private var rotation: Bool = false {
        // 重写设置方法。
        didSet {
            rotationView()
        }
    }
    // 旋转动画
    private func rotationView() {
        var angle = CGFloat(M_PI)
        angle += rotation ? -0.01 : 0.01
        
        UIView.animateWithDuration(0.2) { () -> Void in
            self.downView.transform = CGAffineTransformRotate(self.downView.transform, angle)
        }
    }
    // loading的旋转动画
    private func loadAnimation() {
        let key = "loadingKey"
        if loadingView.layer.animationForKey(key) != nil {
            return
        }
        descLab.text = "正在刷新"
        // 刷新出现
        loadingView.hidden = false
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        // 设置动画
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        loadingView.layer.addAnimation(anim, forKey: key)
    }
    // 停止动画
    private func stopAnimation() {
        descLab.text = "下拉刷新"
        loadingView.hidden = true
        // 移除所有动画
        loadingView.layer.removeAllAnimations()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    // 设置试图
    private func setupView() {
        addSubview(downView)
        addSubview(loadingView)
        addSubview(descLab)
        
        downView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil)
        loadingView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil)
        descLab.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: downView, size: nil)
        sizeToFit()
    }
    private lazy var downView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var loadingView:UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    private lazy var descLab: UILabel = UILabel(title: "下拉刷新", color: UIColor.orangeColor(), fontSize: 14)
}